package com.example.websocket.websocket.ws;

import com.alibaba.fastjson.JSON;
import com.example.websocket.websocket.config.GetHttpSessionConfig;

import com.example.websocket.websocket.pojo.Message;
import com.example.websocket.websocket.pojo.ResultMessage;
import com.example.websocket.websocket.service.MessageRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: websocket
 * @description:
 * @author: fks
 * @create: 2025-03-23 15:46
 **/

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfig.class)
@Component
@Slf4j
public class ChatEndpoint {
    private static MessageRecordService messageRecordService;

    @Autowired
    public void setMessageRecordService(MessageRecordService service) {
        ChatEndpoint.messageRecordService = service;
    }

    public static  final Map<String,Session> onlineUsers =new ConcurrentHashMap<>();
    private HttpSession httpSession;

    /**
     * 建议websocket连接后，被调用
     * @param session
     */
    @OnOpen
    public void onopen(Session session, EndpointConfig config) throws IOException {
        //将session保存
        httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        String username = (String) httpSession.getAttribute("username");
        onlineUsers.put(username,session);
        String message= JSON.toJSONString(getOnlineUsers(username));
        onlineUsers.get(username).getBasicRemote().sendText(message);
    }

    private List<String> getOnlineUsers(String username) {
        List<String> friends = messageRecordService.getChatFriends(username);
        return friends;
    }

    @OnMessage
    public void onmessage(String message) throws IOException {
        Message msg = JSON.parseObject(message, Message.class);
        String touser = msg.getToUser();
        String message1 = msg.getMessage();
        String username = (String) httpSession.getAttribute("username");//获取到当前会话的用户
        //获取消息接收方的session对象
        Session session = onlineUsers.get(touser);
        if (session == null){
            messageRecordService.saveMessage(msg,username);
            return;
        }
        messageRecordService.saveMessage(msg,username);
        ResultMessage result = new ResultMessage();
        result.setData(message1);
        result.setFromUser(username);
        String rel= JSON.toJSONString(result);
        session.getBasicRemote().sendText(rel);
    }

    @OnClose
    public void onclose(Session session){
        //1.从onlineUser里剔除当前用户的session对象
        String username= httpSession.getAttribute("username").toString();
        onlineUsers.remove(username);
    }
}
